<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学海教育 - 学生主页</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    :root {
      --primary: #4a6bff;
      --secondary: #6c757d;
      --success: #28a745;
      --warning: #ffc107;
      --danger: #dc3545;
      --light: #f8f9fa;
      --dark: #343a40;
      --border-radius: 8px;
      --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      --transition: all 0.3s ease;
    }

    body {
      background-color: #f5f7fb;
      color: #333;
      line-height: 1.6;
    }

    .container {
      display: flex;
      min-height: 100vh;
    }

    /* 侧边栏样式 */
    .sidebar {
      width: 250px;
      background: linear-gradient(to bottom, #4a6bff, #3a5bd9);
      color: white;
      padding: 20px 0;
      box-shadow: var(--box-shadow);
      z-index: 100;
    }

    .logo {
      display: flex;
      align-items: center;
      padding: 0 20px 20px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      margin-bottom: 20px;
    }

    .logo i {
      font-size: 28px;
      margin-right: 10px;
    }

    .logo h1 {
      font-size: 20px;
    }

    .nav-links {
      list-style: none;
    }

    .nav-links li {
      padding: 12px 20px;
      margin: 5px 0;
      cursor: pointer;
      transition: var(--transition);
      display: flex;
      align-items: center;
    }

    .nav-links li.active {
      background-color: rgba(255, 255, 255, 0.15);
      border-left: 4px solid white;
    }

    .nav-links li:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }

    .nav-links i {
      margin-right: 12px;
      font-size: 18px;
    }

    /* 主内容区样式 */
    .main-content {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eaeaea;
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .user-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: var(--primary);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
    }
    
    .logout-btn {
      background: var(--danger);
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: var(--border-radius);
      cursor: pointer;
      font-size: 14px;
      transition: var(--transition);
      display: flex;
      align-items: center;
      gap: 6px;
    }
    
    .logout-btn:hover {
      background: #c82333;
      transform: translateY(-1px);
    }

    /* 内容卡片样式 */
    .content-section {
      display: none;
    }

    .content-section.active {
      display: block;
      animation: fadeIn 0.5s ease;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .section-title {
      font-size: 24px;
      margin-bottom: 20px;
      color: var(--dark);
      display: flex;
      align-items: center;
    }

    .section-title i {
      margin-right: 10px;
      color: var(--primary);
    }

    .card-container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
    }

    .card {
      background-color: white;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      overflow: hidden;
      transition: var(--transition);
    }

    .card:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
    }

    .card-header {
      padding: 15px;
      background-color: var(--primary);
      color: white;
    }

    .card-body {
      padding: 15px;
    }

    .card-footer {
      padding: 15px;
      border-top: 1px solid #eaeaea;
      display: flex;
      justify-content: flex-end;
    }

    .btn {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-weight: 500;
      transition: var(--transition);
    }

    .btn-primary {
      background-color: var(--primary);
      color: white;
    }

    .btn-primary:hover {
      background-color: #3a5bd9;
    }

    .btn-success {
      background-color: var(--success);
      color: white;
    }

    .btn-success:hover {
      background-color: #218838;
    }

    .btn-outline {
      background-color: transparent;
      border: 1px solid var(--primary);
      color: var(--primary);
    }

    .btn-outline:hover {
      background-color: var(--primary);
      color: white;
    }

    .progress-bar {
      height: 6px;
      background-color: #e9ecef;
      border-radius: 3px;
      margin: 10px 0;
      overflow: hidden;
    }

    .progress {
      height: 100%;
      background-color: var(--success);
      border-radius: 3px;
    }

    .chapter-list {
      list-style: none;
      margin-top: 15px;
    }

    .chapter-item {
      padding: 10px;
      border-bottom: 1px solid #eaeaea;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chapter-item:last-child {
      border-bottom: none;
    }

    .status-badge {
      padding: 4px 8px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
    }

    .status-completed {
      background-color: #e8f5e9;
      color: var(--success);
    }

    .status-pending {
      background-color: #fff3e0;
      color: #ff9800;
    }

    .assignment-details {
      margin-top: 15px;
    }

    .assignment-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }

    .assignment-info span {
      font-weight: 500;
    }

    .course-card {
      position: relative;
    }

    .course-badge {
      position: absolute;
      top: 15px;
      right: 15px;
      background-color: var(--warning);
      color: var(--dark);
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 500;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .container {
        flex-direction: column;
      }

      .sidebar {
        width: 100%;
        padding: 10px 0;
      }

      .nav-links {
        display: flex;
        justify-content: space-around;
      }

      .nav-links li {
        flex-direction: column;
        text-align: center;
        padding: 10px;
        font-size: 14px;
      }

      .nav-links li.active {
        border-left: none;
        border-bottom: 3px solid white;
      }

      .nav-links i {
        margin-right: 0;
        margin-bottom: 5px;
      }

      .card-container {
        grid-template-columns: 1fr;
      }
    }

    /* 模态框样式 */
    .modal {
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 5% auto;
      padding: 0;
      border-radius: 8px;
      width: 90%;
      max-width: 500px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.3);
    }

    .modal-header {
      padding: 20px;
      border-bottom: 1px solid #e0e0e0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .modal-header h3 {
      margin: 0;
      color: var(--dark);
    }

    .close {
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover {
      color: var(--dark);
    }

    .modal-body {
      padding: 20px;
    }

    .modal-footer {
      padding: 20px;
      border-top: 1px solid #e0e0e0;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: var(--dark);
    }

    .form-control {
      width: 100%;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }

    .form-control:focus {
      outline: none;
      border-color: var(--primary);
      box-shadow: 0 0 0 2px rgba(74, 107, 255, 0.2);
    }
  </style>
</head>
<body>
<div class="container">
  <!-- 侧边导航栏 -->
  <div class="sidebar">
    <div class="logo">
      <i class="fas fa-graduation-cap"></i>
      <h1>学海教育</h1>
    </div>
    <ul class="nav-links">
      <li class="active" data-target="my-courses">
        <i class="fas fa-book-open"></i>
        <span>我的课程</span>
      </li>
      <li data-target="my-assignments">
        <i class="fas fa-tasks"></i>
        <span>我的作业</span>
      </li>
      <li data-target="course-selection">
        <i class="fas fa-plus-circle"></i>
        <span>去选课</span>
      </li>
    </ul>
  </div>

  <!-- 主内容区 -->
  <div class="main-content">
    <div class="header">
      <h2>学生主页</h2>
      <div class="user-info">
        <div class="user-avatar" th:text="${#strings.substring(user.username, 0, 1)}">张</div>
        <span th:text="${user.username} + '同学，欢迎回来！'">张三同学，欢迎回来！</span>
        <button class="logout-btn" onclick="logout()">
          <i class="fas fa-sign-out-alt"></i> 退出登录
        </button>
      </div>
    </div>

    <!-- 我的课程 -->
    <div class="content-section active" id="my-courses">
      <h3 class="section-title">
        <i class="fas fa-book-open"></i>
        我的课程
      </h3>

      <div class="card-container" id="my-courses-list">
        <!-- 课程列表将通过JavaScript动态加载 -->
        <div class="no-courses" style="text-align: center; padding: 40px; color: #666; display: none;">
          <i class="fas fa-book-open" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i>
          <h3>暂无选课</h3>
          <p>您还没有选择任何课程，快去选课页面看看吧！</p>
        </div>
      </div>
    </div>

    <!-- 我的作业 -->
    <div class="content-section" id="my-assignments">
      <h3 class="section-title">
        <i class="fas fa-tasks"></i>
        我的作业
      </h3>

      <!-- 作业列表容器 -->
      <div id="homework-list-container">
        <div id="homework-loading" style="text-align: center; padding: 20px; display: none;">
          <i class="fas fa-spinner fa-spin"></i> 加载中...
        </div>
        <div id="no-homework" style="text-align: center; padding: 40px; color: #666; display: none;">
          <i class="fas fa-clipboard-list" style="font-size: 48px; margin-bottom: 16px; color: #ddd;"></i>
          <h3>暂无作业</h3>
          <p>您还没有任何作业，请先选择课程</p>
        </div>
        <div id="homework-list" class="card-container">
          <!-- 作业列表将通过JavaScript动态加载 -->
        </div>
      </div>
    </div>

    <!-- 去选课 -->
    <div class="content-section" id="course-selection">
      <h3 class="section-title">
        <i class="fas fa-plus-circle"></i>
        去选课
      </h3>

      <div class="card-container" id="selectable-course-list"></div>
    </div>
  </div>
</div>

<!-- 作业提交模态框 -->
<div id="homeworkSubmitModal" class="modal" style="display: none;">
  <div class="modal-content" style="max-width: 600px;">
    <div class="modal-header">
      <h3>提交作业</h3>
      <span class="close" id="closeSubmitModal">&times;</span>
    </div>
    <form id="homeworkSubmitForm">
      <input type="hidden" id="submitHomeworkId">
      <div class="modal-body">
        <div class="form-group">
          <label for="homeworkTitle">作业标题</label>
          <input type="text" id="homeworkTitle" class="form-control" readonly>
        </div>
        <div class="form-group">
          <label for="homeworkContent">作业内容</label>
          <textarea id="homeworkContent" class="form-control" rows="4" readonly></textarea>
        </div>
        <div class="form-group">
          <label for="submitContent">提交内容</label>
          <textarea id="submitContent" class="form-control" rows="6" placeholder="请输入您的作业内容..." required></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" id="cancelSubmit">取消</button>
        <button type="submit" class="btn btn-primary">提交作业</button>
      </div>
    </form>
  </div>
</div>

<script>
  // 选项卡切换功能
  document.addEventListener('DOMContentLoaded', function() {
    const navLinks = document.querySelectorAll('.nav-links li');
    const contentSections = document.querySelectorAll('.content-section');

    navLinks.forEach(link => {
      link.addEventListener('click', function() {
        const targetId = this.getAttribute('data-target');

        // 更新活跃导航项
        navLinks.forEach(item => item.classList.remove('active'));
        this.classList.add('active');

        // 显示对应内容区域
        contentSections.forEach(section => {
          section.classList.remove('active');
          if (section.id === targetId) {
            section.classList.add('active');
          }
        });

        // 切换到"去选课"时加载课程
        if (targetId === 'course-selection') {
          loadSelectableCourses();
        }
        
        // 切换到"我的课程"时加载已选课程
        if (targetId === 'my-courses') {
          loadMyCourses();
        }
        
        // 切换到"我的作业"时加载作业数据
        if (targetId === 'my-assignments') {
          loadMyHomeworks();
        }
      });
    });



    // 加载可选课程列表
    function loadSelectableCourses() {
      fetch('/student/courses/all')
        .then(r => r.json())
        .then(list => {
          const container = document.getElementById('selectable-course-list');
          if (!container) return;
          container.innerHTML = '';
          if (!Array.isArray(list) || list.length === 0) {
            container.innerHTML = '<div style="color:#666;">暂无可选课程</div>';
            return;
          }
          list.forEach(item => {
            const card = document.createElement('div');
            card.className = 'card course-card';
            card.innerHTML = `
              <div class="card-header">
                <h4>${item.title ?? ''}</h4>
                <p>${item.status === 1 ? '已创建' : ''}</p>
              </div>
              <div class="card-body">
                <p>${item.description ?? ''}</p>
              </div>
              <div class="card-footer">
                <button class="btn btn-success" data-course-id="${item.id}">立即选课</button>
              </div>`;
            container.appendChild(card);
          });
        })
        .catch(err => {
          console.error(err);
          const container = document.getElementById('selectable-course-list');
          if (container) container.innerHTML = '<div style="color:#c62828;">加载失败</div>';
        });
    }

    // 选课按钮（事件委托）
    document.getElementById('course-selection').addEventListener('click', function(e) {
      const btn = e.target.closest('.btn-success');
      if (!btn) return;
      const courseId = btn.getAttribute('data-course-id');
      const courseName = btn.closest('.card').querySelector('h4')?.textContent || '';
      
      // 调用后端选课API
      fetch('/student/enroll', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `courseId=${courseId}`
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert(`选课申请已提交：${courseName}`);
          // 可选：禁用按钮或更新状态
          btn.textContent = '已申请';
          btn.disabled = true;
          btn.classList.remove('btn-success');
          btn.classList.add('btn-outline');
        } else {
          alert('选课失败：' + result);
        }
      })
      .catch(err => {
        console.error(err);
        alert('选课失败，请重试');
      });
    });

    // 加载我的课程列表
    function loadMyCourses() {
      fetch('/student/courses/my')
        .then(r => r.json())
        .then(list => {
          const container = document.getElementById('my-courses-list');
          const noCoursesDiv = container.querySelector('.no-courses');
          
          if (!container) return;
          
          // 清空现有内容，但保留no-courses div
          const existingCards = container.querySelectorAll('.card:not(.no-courses)');
          existingCards.forEach(card => card.remove());
          
          if (!Array.isArray(list) || list.length === 0) {
            noCoursesDiv.style.display = 'block';
            return;
          }
          
          noCoursesDiv.style.display = 'none';
          
          list.forEach(item => {
            const card = document.createElement('div');
            card.className = 'card course-card';
            card.innerHTML = `
              <div class="card-header">
                <h4>${item.course_title || '未知课程'}</h4>
                <p>选课时间: ${item.request_time || ''}</p>
              </div>
              <div class="card-body">
                <p>${item.course_description || '暂无描述'}</p>
                <div class="progress-bar">
                  <div class="progress" style="width: 0%"></div>
                </div>
                <p style="margin-top: 10px; font-size: 14px; color: #666;">
                  课程状态: 已选课
                </p>
              </div>
              <div class="card-footer">
                <button class="btn btn-primary enter-course-btn" data-course-id="${item.course_id}">进入课程</button>
              </div>`;
            container.appendChild(card);
          });
        })
        .catch(err => {
          console.error(err);
          const container = document.getElementById('my-courses-list');
          const noCoursesDiv = container.querySelector('.no-courses');
          if (container) {
            noCoursesDiv.style.display = 'block';
            noCoursesDiv.innerHTML = '<i class="fas fa-exclamation-triangle" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i><h3>加载失败</h3><p>无法加载课程信息，请刷新页面重试</p>';
          }
        });
    }

    // 首次进入页面，如果默认就在去选课页，可主动加载
    if (document.getElementById('course-selection').classList.contains('active')) {
      loadSelectableCourses();
    }
    
    // 首次进入页面，如果默认就在我的课程页，主动加载
    if (document.getElementById('my-courses').classList.contains('active')) {
      loadMyCourses();
    }
    
    // 首次进入页面，如果默认就在我的作业页，主动加载
    if (document.getElementById('my-assignments').classList.contains('active')) {
      loadMyHomeworks();
    }

    // 进入课程按钮点击事件
    document.addEventListener('click', function(e) {
      if (e.target.classList.contains('enter-course-btn')) {
        const courseId = e.target.getAttribute('data-course-id');
        if (courseId) {
          window.location.href = `/student/course/${courseId}`;
        }
      }
    });

    // ==================== 作业管理相关函数 ====================
    
    // 加载我的作业列表
    function loadMyHomeworks() {
      const loadingDiv = document.getElementById('homework-loading');
      const noHomeworkDiv = document.getElementById('no-homework');
      const homeworkList = document.getElementById('homework-list');
      
      // 显示加载状态
      loadingDiv.style.display = 'block';
      noHomeworkDiv.style.display = 'none';
      homeworkList.innerHTML = '';
      
      fetch('/student/homeworks')
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          return response.json();
        })
        .then(data => {
          loadingDiv.style.display = 'none';
          
          if (typeof data === 'string') {
            // 错误信息
            homeworkList.innerHTML = `
              <div style="text-align: center; color: #c62828; padding: 20px;">
                <i class="fas fa-exclamation-triangle"></i>
                <div>${data}</div>
              </div>`;
            return;
          }
          
          if (!Array.isArray(data) || data.length === 0) {
            noHomeworkDiv.style.display = 'block';
            return;
          }
          
          data.forEach(homework => {
            const homeworkCard = createHomeworkCard(homework);
            homeworkList.appendChild(homeworkCard);
          });
        })
        .catch(error => {
          loadingDiv.style.display = 'none';
          homeworkList.innerHTML = `
            <div style="text-align: center; color: #c62828; padding: 20px;">
              <i class="fas fa-exclamation-triangle"></i>
              <div>加载失败: ${error.message}</div>
            </div>`;
        });
    }
    
    // 创建作业卡片
    function createHomeworkCard(homework) {
      const card = document.createElement('div');
      card.className = 'card';
      
      // 计算作业状态
      const now = new Date();
      const ddlTime = new Date(homework.ddl_time);
      const timeDiff = ddlTime.getTime() - now.getTime();
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
      
      let statusClass, statusText, buttonText, buttonClass;
      
      if (homework.submitted_at) {
        // 已提交
        if (homework.score) {
          statusClass = 'status-graded';
          statusText = '已批改';
          buttonText = '查看成绩';
          buttonClass = 'btn btn-outline';
        } else {
          statusClass = 'status-submitted';
          statusText = '已提交';
          buttonText = '查看提交';
          buttonClass = 'btn btn-outline';
        }
      } else if (timeDiff < 0) {
        // 已过期
        statusClass = 'status-expired';
        statusText = '已过期';
        buttonText = '查看详情';
        buttonClass = 'btn btn-outline';
      } else if (daysDiff <= 1) {
        // 即将截止
        statusClass = 'status-pending';
        statusText = '即将截止';
        buttonText = '立即提交';
        buttonClass = 'btn btn-primary';
      } else {
        // 进行中
        statusClass = 'status-pending';
        statusText = '进行中';
        buttonText = '提交作业';
        buttonClass = 'btn btn-primary';
      }
      
      card.innerHTML = `
        <div class="card-header">
          <h4>${homework.title || '作业'}</h4>
          <p>截止日期: ${formatDateTime(homework.ddl_time)}</p>
        </div>
        <div class="card-body">
          <p>${homework.content || ''}</p>
          
          <div class="assignment-details">
            <div class="assignment-info">
              <span>状态:</span>
              <span class="status-badge ${statusClass}">${statusText}</span>
            </div>
            <div class="assignment-info">
              <span>总分:</span>
              <span>${homework.total_score}分</span>
            </div>
            ${homework.submitted_at ? `
              <div class="assignment-info">
                <span>提交时间:</span>
                <span>${formatDateTime(homework.submitted_at)}</span>
              </div>
            ` : `
              <div class="assignment-info">
                <span>剩余时间:</span>
                <span>${daysDiff > 0 ? daysDiff + '天' : '已过期'}</span>
              </div>
            `}
            ${homework.score ? `
              <div class="assignment-info">
                <span>得分:</span>
                <span>${homework.score}/${homework.total_score}</span>
              </div>
            ` : ''}
            ${homework.feedback ? `
              <div class="assignment-info">
                <span>教师反馈:</span>
                <span>${homework.feedback}</span>
              </div>
            ` : ''}
          </div>
        </div>
        <div class="card-footer">
          <button class="${buttonClass}" data-homework-id="${homework.id}" data-action="${homework.submitted_at ? 'view' : 'submit'}">
            ${buttonText}
          </button>
        </div>
      `;
      
      return card;
    }
    
    // 格式化日期时间
    function formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '';
      const date = new Date(dateTimeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
    
    // 打开作业提交模态框
    function openSubmitModal(homeworkId) {
      const modal = document.getElementById('homeworkSubmitModal');
      const form = document.getElementById('homeworkSubmitForm');
      
      // 重置表单
      form.reset();
      document.getElementById('submitHomeworkId').value = homeworkId;
      
      // 获取作业详情
      fetch(`/student/homework/${homeworkId}/submission`)
        .then(response => response.json())
        .then(data => {
          if (typeof data === 'string') {
            alert('获取作业详情失败: ' + data);
            return;
          }
          
          // 填充作业信息
          document.getElementById('homeworkTitle').value = data.title || '';
          document.getElementById('homeworkContent').value = data.content || '';
          
          // 如果已经提交过，显示之前的内容
          if (data.content_text) {
            document.getElementById('submitContent').value = data.content_text;
          }
          
          modal.style.display = 'block';
        })
        .catch(error => {
          console.error('获取作业详情失败:', error);
          alert('获取作业详情失败: ' + error.message);
        });
    }
    
    // 提交作业
    function submitHomework() {
      const form = document.getElementById('homeworkSubmitForm');
      const homeworkId = document.getElementById('submitHomeworkId').value;
      const contentText = document.getElementById('submitContent').value;
      
      if (!contentText.trim()) {
        alert('请输入作业内容');
        return;
      }
      
      const submitBtn = form.querySelector('button[type="submit"]');
      const originalText = submitBtn.textContent;
      submitBtn.disabled = true;
      submitBtn.textContent = '提交中...';
      
      const data = {
        homeworkId: homeworkId,
        contentText: contentText,
        fileUrl: null
      };
      
      fetch('/student/homework/submit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(data)
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert('作业提交成功！');
          closeModal('homeworkSubmitModal');
          // 重新加载作业列表
          loadMyHomeworks();
        } else {
          alert('提交失败：' + result);
        }
      })
      .catch(error => {
        console.error('提交作业失败:', error);
        alert('提交失败：' + error.message);
      })
      .finally(() => {
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
      });
    }
    
    // 关闭模态框
    function closeModal(modalId) {
      document.getElementById(modalId).style.display = 'none';
    }
    
    // 作业相关事件监听
    document.addEventListener('click', function(e) {
      if (e.target.matches('button[data-action="submit"]')) {
        const homeworkId = e.target.getAttribute('data-homework-id');
        openSubmitModal(homeworkId);
      } else if (e.target.matches('button[data-action="view"]')) {
        const homeworkId = e.target.getAttribute('data-homework-id');
        // 这里可以打开查看详情的模态框
        alert('查看作业详情功能待实现');
      }
    });
    
    // 作业提交模态框事件监听
    const submitModal = document.getElementById('homeworkSubmitModal');
    const submitForm = document.getElementById('homeworkSubmitForm');
    
    document.getElementById('closeSubmitModal').addEventListener('click', () => {
      closeModal('homeworkSubmitModal');
    });
    document.getElementById('cancelSubmit').addEventListener('click', () => {
      closeModal('homeworkSubmitModal');
    });
    submitForm.addEventListener('submit', function(e) {
      e.preventDefault();
      submitHomework();
    });
  });
  
  // 退出登录函数
  function logout() {
    if (confirm('确定要退出登录吗？')) {
      window.location.href = '/logout';
    }
  }
</script>
</body>
</html>·